<?php
class User extends AppModel {

    public $name = 'User';
    public $recursive = -1;
    public $actsAs = array('Acl'=>'requester');
    public $validate = array(
        'username' => array('notempty'),
        'password' => array('notempty'),
        'group_id' => array('notempty')
    );

    public $belongsTo = array(
        'Group' => array(
            'className' => 'Group',
            'foreignKey' => 'group_id',
            'counterCache' => true,
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    // The Associations below have been created with all possible keys,
    // those that are not needed can be removed
    public $hasMany = array(
        'Post' => array(
            'className' => 'Post',
            'foreignKey' => 'user_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

    public function afterSave($created){
        $aro =& $this->Aro;
        if(!$created){
            // its an edit, we have to update the tree
            $data = $this->read();
            $parent_id = $data['User']['group_id'];
            $aro_record = $aro->findByAlias($this->name.':'.$this->id);
            $parent_record = $aro->findByAlias('Group:'.$parent_id);
            if(!empty($aro_record)){
                $parent_id = '0';
                if(!empty($parent_record)){
                    $parent_id = $parent_record['Aro']['id'];
                }
                // just changing parents
                $aro->save(array('parent_id' => $parent_id,'id' => $aro_record['Aro']['id']));
            }
        }
        return true;
    }
    public function parentNode(){
        // This should be the alias of the parent $model::$id
        $data = $this->read();
        // This needs to be unique
        return 'Group:'.$data['User']['group_id'];
    }

}
?>